package com.example.element.module.jetpack.viewmodel

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.lifecycle.ViewModelProvider
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActJetpackViewmodelBinding
import com.example.element.module.jetpack.lifecycles.MyObserver

/**
 * ViewModel、lifecycle生命周期监听
 */
class ViewModelActivity : AbsActivity<ActJetpackViewmodelBinding>() {

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, ViewModelActivity::class.java))
        }
    }

    lateinit var viewModel: TestViewModel
    lateinit var sp: SharedPreferences

    override fun getLayoutId() = R.layout.act_jetpack_viewmodel

    override fun main() {
        sp = getPreferences(Context.MODE_PRIVATE)
        val countReserved = sp.getInt("count_reserved", 0)
//        viewModel = ViewModelProvider(this).get(TestViewModel::class.java)
        viewModel = ViewModelProvider(this, TestViewModelFactory(countReserved)).get(TestViewModel::class.java)
        refreshCounter()
        lifecycle.addObserver(MyObserver())
    }

    override fun initListener() {
        mBinding.plusOneBtn.setOnClickListener {
            viewModel.counter++
            refreshCounter()
        }

        mBinding.clearCount.setOnClickListener {
            viewModel.counter = 0
            refreshCounter()
        }
    }

    private fun refreshCounter() {
        mBinding.infoText.text = viewModel.counter.toString()
    }

    override fun onPause() {
        super.onPause()
        sp.edit().putInt("count_reserved", viewModel.counter).apply()
    }
}